import { ref } from 'vue'
import { v4 } from 'uuid'
import _ from 'lodash-es'
import Api from '@/libs/api'
import Tool from '@/libs/utils/Tool'
import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import type { GoodsEditForm } from './types'

export const useGoodsSkuAttributes = (editForm: Ref<GoodsEditForm>, conf: any) => {
	const { t } = useI18n()

	const addAttrK = () => {
		if (editForm.value.attrs.length === conf.maxAttrKLen) {
			Api.notify(t('通知.sku规格限制', { maxAttrKLen: conf.maxAttrKLen }))
		} else {
			const attr = {
				id: 0,
				uuid: v4(),
				isEditing: true,
				vEditingCount: 0,
				k: '',
				v: []
			}
			editForm.value.attrs.push(attr)
		}
	}

	const delAttrK = (key: number) => {
		editForm.value.attrs.splice(key, 1)
	}

	const doSaveAttrK = (key: number) => {
		if (!editForm.value.attrs[key].k) {
			Api.notify(t('通知.sku属性名必填'))
		} else {
			const attrKKs = editForm.value.attrs.map(item => item.k)
			if (Tool.hasDuplicates(attrKKs)) {
				Api.notify(t('通知.sku属性名重复'))
				return false
			}
			editForm.value.attrs[key].isEditing = false
		}
		return true
	}

	const addAttrV = (kKey: number) => {
		if (editForm.value.attrs[kKey].v.length === conf.maxAttrVLen) {
			Api.notify(t('通知.sku属性值限制', { maxAttrVLen: conf.maxAttrVLen }))
		} else {
			const attrV = {
				id: 0,
				uuid: v4(),
				isEditing: true,
				isSel: false,
				value: ''
			}
			editForm.value.attrs[kKey].v.push(attrV)
			editForm.value.attrs[kKey].vEditingCount++
		}
	}

	const editAttrV = (kKey: number, vKey: number) => {
		editForm.value.attrs[kKey].v[vKey].isEditing = true
		editForm.value.attrs[kKey].vEditingCount++
	}

	const doSaveAttrV = (kKey: number, vKey: number) => {
		if (!editForm.value.attrs[kKey].v[vKey].value) {
			Api.notify(t('通知.sku属性值必填'))
		} else {
			const attrVValues = editForm.value.attrs[kKey].v.map(item => item.value)
			if (Tool.hasDuplicates(attrVValues)) {
				Api.notify(t('通知.sku属性值重复'))
				return false
			}
			editForm.value.attrs[kKey].v[vKey].isEditing = false
			editForm.value.attrs[kKey].vEditingCount--
		}
		return true
	}

	const delAttrV = (kKey: number, vKey: number) => {
		editForm.value.attrs[kKey].v.splice(vKey, 1)
		editForm.value.attrs[kKey].vEditingCount--
	}

	const selAttrV = (kKey: number, vKey: number) => {
		if (editForm.value.attrs[kKey].v[vKey].isSel === false) {
			editForm.value.attrs[kKey].v.forEach(item => {
				item.isSel = false
			})
			editForm.value.attrs[kKey].v[vKey].isSel = true
		} else {
			editForm.value.attrs[kKey].v.forEach(item => {
				item.isSel = false
			})
			editForm.value.attrs[kKey].v[vKey].isSel = false
		}
	}

	return {
		addAttrK,
		delAttrK,
		doSaveAttrK,
		addAttrV,
		editAttrV,
		doSaveAttrV,
		delAttrV,
		selAttrV
	}
}
